//
//  HLBaseViewController.m
//  s.
//
//  Created by pro on 2021/1/15.
//  Copyright © 2021 hailuo. All rights reserved.
//

#import "BaseViewController.h"
#import "JYLoadingView.h"
#import "UINavigationComponent.h"
static int animationTime = 10;

@interface BaseViewController ()
@property (weak, nonatomic) JYLoadingView *loadV;
//@property (weak, nonatomic) BEEmptyTipView *emptyView;
@property (weak, nonatomic) UIView *lineView;
@property (weak, nonatomic) LNavigationBar *customBar; // 自定义导航
@end

@implementation BaseViewController

- (UIStatusBarStyle)preferredStatusBarStyle
{
    if (@available(iOS 13.0, *)) {
        return UIStatusBarStyleDarkContent;
    } else {
        return UIStatusBarStyleDefault;
    }
}
- (void)dealloc {
    HLInfoLog(@"%@ dealloc",NSStringFromClass(self.class));
}

+ (instancetype)newCtl:(id)info{
    BaseViewController *obj = [self class].new;
    obj.metaInfo = info;
    return obj;
}

#pragma --mark UIView->kl_action事件回调处理,全局调用能力,如需个性化处理事件,请在子类重写 ----
- (void)handleCommand:(NSDictionary *)action{
    [self handleCommand:action handle:nil];
}
- (void)handleCommand:(NSDictionary *)action handle:(id)handle{
    Class cls = (id)objc_getClass("JYRunEngine");
    NSAssert(cls != nil, @"无法找到类HLRunEngine");
    ((void(*)(id,SEL,id,id))objc_msgSend)(cls,NSSelectorFromString(@"handleCommand:handle:"),action,handle);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.navigationController &&
        self.navigationController.viewControllers.count > 1) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"backWhite"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] style:UIBarButtonItemStylePlain target:self action:@selector(popViewController)];
        self.navigationItem.leftBarButtonItem.tintColor = jy_HexColor(@"#333333");
    }
    
    self.view.backgroundColor = JYColor_VC();
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.modalPresentationCapturesStatusBarAppearance = NO;
    
    self.popGestureEnabled = YES;
    
    [self __setupView];
    
//    [self initData];
//    [self initUI];
//    [self requestData];
    
}

#pragma mark - 统一title风格

- (void)setNavTitle:(NSString *)title
{
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = title;
    titleLab.textColor = jy_HexColor(@"#333333");
    titleLab.font = U_bfont(18);
    titleLab.textAlignment = NSTextAlignmentCenter;
    titleLab.backgroundColor = [UIColor clearColor];
    if ([title isKindOfClass:[NSAttributedString class]]) {
        titleLab.attributedText = (NSAttributedString *)title;
    }
    self.navigationItem.titleView = titleLab;
}

- (void)__setupView {
    if (self.showLine) {
        [self lineView];
    }
}

#pragma mark - 全局的返回按钮
- (void)initBackBarItem:(NSString *)title
{
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"backWhite"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(popViewController)];
    
    // fansj 根据tintColor来设置返回按钮的颜色
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"backWhite"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] style:UIBarButtonItemStylePlain target:self action:@selector(popViewController)];
    self.navigationItem.leftBarButtonItem.tintColor = jy_HexColor(@"#333333");
    self.navigationItem.title = title;
}
- (void)blackBacker
{
//    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back_black"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(popViewController)];
}
#pragma mark - 全局的右上角按钮
-(void)initRightBarButtonItemWithButtonIcon:(id)buttonIcon block:(void(^)(UIButton *rightButton))RightButtonBlock
{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    if ([buttonIcon isKindOfClass:[NSString class]]) {
        rightButton.frame = CGRectMake(0, 0, 70, 30);
        rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [rightButton setTitle:buttonIcon forState:UIControlStateNormal];
        [rightButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        rightButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        rightButton.titleLabel.textAlignment = NSTextAlignmentRight;
    }else if ([buttonIcon isKindOfClass:[UIImage class]]){
        rightButton.frame = CGRectMake(0, 0, 25, 25);
        [rightButton setBackgroundImage:buttonIcon forState:UIControlStateNormal];
    }
    
    [rightButton setBackgroundColor:[UIColor clearColor]];
    [rightButton addBlockForControlEvents:UIControlEventTouchUpInside block:^(id  _Nonnull sender) {
        RightButtonBlock(sender);
    }];
    UIBarButtonItem *rightBarBtnItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = rightBarBtnItem;
}
#pragma mark - 返回按钮点击事件
- (void)popViewController {
    [self back];
}

- (void)back{
    [self backWithAnimated:YES];
}

- (void)backWithAnimated:(BOOL)animated{
    [self backWithAnimated:animated completion:nil];
}

- (void)backWithAnimated:(BOOL)animated completion: (void (^)(void))completion{
    if (self.navigationController) {
        if (self.navigationController.viewControllers.count!=1) {
            [self.navigationController popViewControllerAnimated:animated];
            if (completion) {
                completion();
            }
        }else{
            [self.navigationController dismissViewControllerAnimated:animated completion:completion];
        }
    }else{
         [self dismissViewControllerAnimated:animated completion:completion];
    }
}
#pragma mark - 移除当前视图
-(void)removeSelfContrller
{
    // 延迟的目的是防止影响到新的Controller
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSMutableArray *navigationArray = [[NSMutableArray alloc] initWithArray: self.navigationController.viewControllers];
        // 移除当前的controller
        [navigationArray removeObject:self];
        self.navigationController.viewControllers = navigationArray;
    });
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.translucent = NO;
    //去除导航栏底部横线
//    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
//    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
//    [self.navigationController.navigationBar setBackgroundImage: [UIImage imageNamed:@"my_bg"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController setNavigationBarHidden:self.bar_hidden animated:animated];
    
    [self.view bringSubviewToFront:self.bar];
    HLFileLog(@"👉 currentVc => %@", NSStringFromClass([self class]));
   
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.bar_hidden) {
        if ([self jy_pushOrPopIsHidden] == NO) {
            [self.navigationController setNavigationBarHidden:NO animated:animated];
        }
    }
}
 
- (BOOL)jy_pushOrPopIsHidden {
    NSArray *viewControllers = self.navigationController.viewControllers;
    if (viewControllers.count > 0) {
        BaseViewController * vc = viewControllers.lastObject;
        return vc.bar_hidden;
    }
    return NO;
}

- (void)setNavigationBarColor:(UIColor *)color {
    // fansj
    if (@available(iOS 15.0, *)) {
        self.navigationController.navigationBar.standardAppearance.backgroundColor = color;
        self.navigationController.navigationBar.scrollEdgeAppearance.backgroundColor = color;
    } else {
        // Fallback on earlier versions
        self.navigationController.navigationBar.barTintColor = color;
    }
}

#pragma mark - 懒加载
- (LNavigationBar *)customBar {
    if (!_customBar) {
        LNavigationBar *obj = [[LNavigationBar alloc] init];
        [self.view addSubview:_customBar = obj];
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            kMakeLTRV(0);
            kMakeHV(self.jy_bar_h);
        }];
        obj.backgroundColor = KLColor(@"FFFFFF");//KLColor(@"#f5f5f5");
        obj.hidden = [self jy_bar_hidden];
        obj.backAction = kMsgForward(@"back", WKProxy(self));
        obj.layer.zPosition = 1000;
        if (self.navigationController &&
            self.navigationController.viewControllers.count > 1) {
            obj.backHidden = NO;
        }else {
            obj.backHidden = YES;
        }
    }
    return _customBar;
}

- (UIButton *)rightBtn{
    if (!_rightBtn) {
        UIButton *obj = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.customBar addSubview:_rightBtn = obj];
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            kMakeRV(-20);
            kMakeBV(0);
            kMakeHV(44);
        }];
        obj.titleLabel.font = U_font(14);
        [obj setTitleColor:KLColor(@"#333333") forState:(UIControlStateNormal)];
    }
    return _rightBtn;
}

- (UIView *)lineView {
    if (!_lineView) {
        UIView *obj = [UIView new];
        [self.view addSubview:_lineView = obj];
        obj.layer.zPosition = 100;
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            kMakeLTRV(0);
            kMakeHV(1);
        }];
        obj.backgroundColor = KLColorWithAlpha(@"#000000",0.1);
    }
    return _lineView;
}

- (JYLoadingView *)loadV {
    if (!_loadV) {
        JYLoadingView *obj = [[JYLoadingView alloc] init];
        [self.view addSubview:_loadV = obj];
        obj.layer.zPosition = 1001;
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.right.left.mas_equalTo(0);
            make.top.mas_equalTo(0);
        }];
    }
    return _loadV;
}

//- (BEEmptyTipView *)emptyView{
//    if (!_emptyView) {
//        NSString *clsStr = nil;
//        if (self.emptyClsBlock) {
//            clsStr = self.emptyClsBlock();
//        }
//        BEEmptyTipView *obj = nil;
//        if (clsStr) {
//            Class cls = NSClassFromString(clsStr);
//            id myobjc = ((id (*)(id, SEL))objc_msgSend)(cls, @selector(alloc));
//            obj = ((id (*)(id, SEL))objc_msgSend)(myobjc, @selector(init));
//        }else {
//            obj = [[BEEmptyTipView alloc] init];
//        }
//        [self.view addSubview:_emptyView = obj];
//        obj.layer.zPosition = 1000;
//        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
//            if (self.emptyViewBlock) {
//                self.emptyViewBlock(make);
//                self.emptyViewBlock = nil;
//            }else {
//                kMakeWHV(200, 200);
//                kMakeCenterXV(0);
//                kMakeCenterYV(0);
//            }
//        }];
//        obj.userInteractionEnabled = NO;
//        
//        if (self.emptyImageBlock) {
//            [obj.imageView mas_remakeConstraints:^(MASConstraintMaker *make) {
//                self.emptyImageBlock(make);
//            }];
//        }
//    }
//    return _emptyView;
//}

- (void)setShowPageLoding:(BOOL)showPageLoding{
    _showPageLoding = showPageLoding;
    self.loadV.showLoading = showPageLoding;
}

- (void)setShowNoContent:(BOOL)showNoContent {
    _showNoContent = showNoContent;
    if (_showNoContent && !self.jy_haveData) {
//        self.emptyView.hidden = NO;
//        [self.emptyView setupImage:self.empty_image];
//        [self.emptyView setupEmptyString:@"暂无数据"];
//        if (_emptyView) {
//            _emptyView.zh_action = self.empty_action;
//        }
    }else{
//        _emptyView.hidden = YES;
    }
}

- (BOOL)showLine {
    return NO;
}

- (void)setJy_title:(NSString *)hl_title {
    self.customBar.title = hl_title;
}

- (void)setPopGestureEnabled:(BOOL)popGestureEnabled{
    _popGestureEnabled = popGestureEnabled;
    [self.navigationController popGesture:popGestureEnabled];
}
- (void)removeTopVcCount:(NSInteger)count
{
    if (self.navigationController.viewControllers.count <= 2) {
        return;
    }
    if (count < 1 || count > self.navigationController.viewControllers.count - 2) {
        return;
    }
    
    NSMutableArray *copyVcs = [self.navigationController.viewControllers mutableCopy];
    
    [copyVcs removeObjectsInRange:NSMakeRange(copyVcs.count - 1 - count, count)];

    [self.navigationController setViewControllers:copyVcs animated:NO];
}
- (void)removeTopVcUntil:(NSString *)vcName
{
    if (!vcName) { return; }
    Class cls = NSClassFromString(vcName);
    if (!cls) { return; }
    if (self.navigationController.viewControllers.count <= 2) { return; }
    
    NSMutableArray *copyVcs = [self.navigationController.viewControllers mutableCopy];
    NSInteger index = -1;
    for (NSInteger i = copyVcs.count - 2; i > 0; i --) {
        UIViewController *aVc = copyVcs[i];
        if ([aVc isKindOfClass:[cls class]]) {
            index = i;
            break;
        }
    }
    if (index < 0) {
        return;
    }
    NSInteger start = index + 1;
    [copyVcs removeObjectsInRange:NSMakeRange(start, copyVcs.count - 1 - start)];
    [self.navigationController setViewControllers:copyVcs animated:NO];
}

/** 是否第一次加载controller */
- (BOOL)isFirstLoad {
    return self.isMovingToParentViewController;
}

#pragma mark - 只读
- (BOOL)jy_haveData {return NO;}
- (NSString *)empty_image{return @"noData";}
- (NSDictionary *)empty_action{return nil;};
//- (BEEmptyTipView *)emptyV {return _emptyView;}
- (BOOL)bar_hidden {return YES;}
- (BOOL)jy_bar_hidden {return NO;}
- (CGFloat)jy_bar_h {return klStatusBarHeight+44;}
- (LNavigationBar *)bar {
    if (_customBar) {
        return _customBar;
    }
    return nil;
}


@end
